package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.PreparedStatement;

/**
 * @author shkstart
 * 删除文章
 * @create 2023-01-13-14:40
 */
@WebServlet("/delart")
public class DelArticleServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg = "未知参数 delarticleservlet";
        int data = 0;
        //验证当前的登录状态以及文章的所属是否是同一个人
        UserInfo userInfo = SessionUtils.getLoginUser(req);
        if (userInfo != null) {
            //1.得到参数并进行非空校验
            String aidstr = req.getParameter("aid");
            if (!StrUtil.isBlank(aidstr)) {
                //根据传递的参数对文章进行删除
                int aid = Integer.valueOf(aidstr);
                if (aid > 0) {

                    //2.1得到连接
                    Connection connection = DBUtils.getConnection();
                    //2.2拼接sql,得到执行器(要判断文章的归属是否是同一个人）
                    String sql = "delete from article where aid = ? and uid = ?";
                    PreparedStatement statement = connection.prepareStatement(sql);
                    //2.3执行sql,得到执行结果
                    statement.setInt(1, aid);
                    statement.setInt(2, userInfo.getUid());

                    data = statement.executeUpdate();
                    //2.4关闭连接
                    DBUtils.close(null, statement, connection);
                } else {
                    msg = "参数非法";
                }
            } else {
                msg = "参数错误";
            }
        }else {
            msg = "当前用户未登录";
        }
        //3.将结果返回
        resp.setContentType(AppVar.RESP_JSON_UTF8);
        resp.getWriter().println(
                JSONUtil.toJsonStr(
                        ResultUtils.toResult(200, data, msg)
                )
        );
    }
}
